#ifndef DOUYIN_H
#define DOUYIN_H
#include "libs/core/model/modeltype.h"

// 压缩Script Source Code
// const auto code = DouYin::webEntry().script.source_code;
// const auto ba = qCompress(code.toUtf8());
// const auto ba2 = ba.toHex();
// qDebug() << QString::fromLatin1(ba2);

class DouYin
{
public:
    static yc::LiveWebEntry webEntry()
    {
        return yc::LiveWebEntry { yc::DOUYIN_PLATFORM_TYPE,
                                  QString("DouYin"),
                                  QString("https://live.douyin.com/%1"),
                                  QString("https://www.douyin.com/user/%1"),
                                  yc::DESKTOP_USER_AGENT_TYPE,
                                  yc::WebScript { 0, R"((function(objectName, interval) {
    // 只需要处理'live.douyin.com'域名
    if (window.location.href.indexOf('live.douyin.com') < 0) {
        return;
    }

    const METHOD_SET_LIVE_INFO = 'setLiveInfo';
    const METHOD_SET_LIVE_STATUS = 'setLiveStatus';

    // C++方法
    const MethodNames = {
        setLiveInfo: `${objectName}.${METHOD_SET_LIVE_INFO}`,
        setLiveStatus: `${objectName}.${METHOD_SET_LIVE_STATUS}`
    };

    // 定义命名空间
    window.YCLiveUtils = window.YCLiveUtils || {};

    // 提取 roomInfo 对象的函数
    window.YCLiveUtils.extractRoomInfoJson = function(content) {
        let keyword = '\\"roomInfo\\":';

        // Find the start index of "roomInfo": { and ensure it starts right after :
        const startIndex = content.indexOf(keyword);
        if (startIndex === -1) {
            console.log('No roomInfo object found in the content.');
            return '';
        }

        // Initialize variables for finding the matching closing brace
        let braceCount = 0; // Start with 1 because we are already past the opening {
        let endIndex = startIndex + keyword.length;

        // Iterate through the string starting from just after the first {
        for (; endIndex < content.length; endIndex++) {
            const char = content[endIndex];
            if (char === '{') {
                braceCount++;
            } else if (char === '}') {
                braceCount--;
                if (braceCount === 0) {
                    break;
                }
            }
        }

        // If we didn't find a proper closure, log an error and return null
        if (braceCount !== 0) {
            console.error("No valid JSON object found.");
            return '';
        }

        // Extract the JSON string
        const jsonString = content.substring(startIndex + keyword.length, endIndex + 1);
        return jsonString.replace(/\\\\\\"/g, '$$$').replace(/\\"/g, '"');
    };

    // 提取流 URL 信息的函数
    window.YCLiveUtils.extractStreamUrls = function(streamUrlObj = {}) {
        return {
            flvPullUrl: streamUrlObj?.flv_pull_url ?? null,
            defaultResolution: streamUrlObj?.default_resolution ?? '',
            hlsPullUrlMap: streamUrlObj?.hls_pull_url_map ?? {},
            hlsPullUrl: streamUrlObj?.hls_pull_url ?? '',
            extra: streamUrlObj?.extra ?? {}
        };
    };

    // 提取用户信息的函数
    window.YCLiveUtils.extractUserInfo = function(userId, userSecUid, userNickname, userAvatar) {
        return {
            platformId: userId || '',
            platformSecUid: userSecUid || '',
            nickname: userNickname || '',
            avatar: userAvatar || ''
        };
    };

    // 提取 room 相关信息的函数
    window.YCLiveUtils.extractRoomInfo = function(parsedJson) {
        const {
            room: {
                id_str: roomIdStr = '',
                status = 0,
                title = '',
                stream_url: streamUrl = {},
                like_count: likeCount = 0,
                owner: {
                    id_str: ownerId = '',
                    sec_uid: ownerSecUid = '',
                    nickname: ownerNickname = '',
                    avatar_thumb: {
                        url_list: [ownerFirstThumbUrl = null, ...ownerRestThumbUrls] = []
                    } = {}
                } = {},
                room_view_stats: { display_value: viewCount = 0 } = {}
            } = {},
            roomId: platformId = '',
            web_rid: platformWebRid = '',
            anchor: {
                id_str: anchorId = '',
                sec_uid: anchorSecUid = '',
                nickname: anchorNickname = '',
                avatar_thumb: {
                    url_list: [anchorFirstThumbUrl = null, ...anchorRestThumbUrls] = []
                } = {}
            } = {},
            qrcode_url: qrcodeUrl = '',
            web_stream_url: webStreamUrl = {}
        } = parsedJson;

        return {
            platformId,
            platformWebRid,
            status,
            title,
            viewCount,
            likeCount,
            owner: window.YCLiveUtils.extractUserInfo(ownerId, ownerSecUid, ownerNickname, ownerFirstThumbUrl),
            anchor: window.YCLiveUtils.extractUserInfo(anchorId, anchorSecUid, anchorNickname, anchorFirstThumbUrl),
            qrcodeUrl,
            streamUrl: window.YCLiveUtils.extractStreamUrls(streamUrl),
            webStreamUrl: window.YCLiveUtils.extractStreamUrls(webStreamUrl)
        };
    };

    // 设置 roomInfo 的主函数
    window.YCLiveUtils.setRoomInfo = function(json) {
        try {
            const parsedJson = JSON.parse(json);

            // 提取 room 相关信息
            const roomInfo = window.YCLiveUtils.extractRoomInfo(parsedJson);

            // 调用方法并传递 JSON 字符串
            window.YCApp.invokeMethod(MethodNames.setLiveInfo, JSON.stringify(roomInfo));
        } catch (e) {
            console.error('Error parsing JSON or missing required fields:', e, 'Original JSON:', json);
            // 如果解析失败或缺少必要字段，调用默认方法
            window.YCApp.invokeMethod(MethodNames.setLiveInfo, '');
        }
    };

    // 获取在线观众数量
    window.YCLiveUtils.setLiveStatus = function(){
        let target = document.querySelector('#chatroom div[data-e2e="live-room-audience"]');
        if (target && target.textContent) {
            window.YCApp.invokeMethod(MethodNames.setLiveStatus, target.textContent);
        } else {
            window.YCApp.invokeMethod(MethodNames.setLiveStatus, '-1');
        }
    }

    window.YCLiveUtils.parseLiveInfo = function() {
        // 获取直播信息
        const keyword = 'roomInfo';

        // 获取所有不带 src 属性且包含指定关键字的 script 标签
        const scripts = Array.from(document.querySelectorAll('script:not([src])'))
                             .filter(script => script.innerHTML.includes(keyword));

        for (const script of scripts) {
            try {
                const json = window.YCLiveUtils.extractRoomInfoJson(script.innerHTML);
                if (json.length > 10) {
                    const startIndex = json.indexOf('"id_str":');
                    if (startIndex > -1) {
                        const endIndex = json.indexOf('"', startIndex + 10);
                        const len = endIndex - startIndex - 11;
                        if (len > 4) {
                            const id_str = json.substring(startIndex + 10, endIndex).trim();
                            if (id_str && !id_str.includes('undefined')) {
                                // window.YCApp.invokeMethod(MethodNames.setLiveInfo, json);
                                window.YCLiveUtils.setRoomInfo(json);
                                return; // 找到后立即返回
                            }
                        }
                    }
                }
            } catch (error) {
                console.error(`Error processing script at index ${scripts.indexOf(script)}:`, error);
            }
        }
    }

    // 解析liveInfo
    window.YCLiveUtils.parseLiveInfo();

    // 安装状态定时器
    if (interval > 0 && typeof window.qt !== 'undefined' && typeof window.YCApp !== 'undefined') {
        setInterval(window.YCLiveUtils.setLiveStatus, interval);
    }
})('%1',%2);)" } };
    }
};

#endif // DOUYIN_H
